# Darren
# 2025年02月24日09时51分03秒

list1 = [1, 3, 2, 4, 5, 3, 2]
print(sorted(list1))  # sorted 返回新的有序表 (sort返回None,只针对原表做修改)
print(list1)  # 原表保持不变
print('-' * 50)

print(sorted({1: 'D', 2: 'B', 3: 'B', 5: 'E', 4: 'A'}))  # 针对字典的关键字排序
print('-' * 50)

str_list = "This is a test string from Andrew".split()
print(sorted(str_list))
# str.lower() 将字符串大写字母改为小写并返回
print(sorted(str_list, key=str.lower))  # key:比较规则函数，不改变比较对象，属于回调函数
print('-' * 50)

# 列表嵌套元组
# 竖选：shift+alt
student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
# 匿名函数：无需复用,直接通过表达式定义，提高代码的阅读效率
# lambda 表达式属于匿名函数 lambda 参数（形参）：表达式（返回值）
print(sorted(student_tuples, key=lambda x: x[2]))  # 按2号下标进行排序
print('-' * 50)


# 对象的排序
class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def __repr__(self):
        # 类似str,但可返回非字符串类型
        return repr((self.name, self.grade, self.age))  # 返回元组


student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10)
]  # 对象列表
s = student_objects[0]
print(s)  # repr方法，直接将对象属性转化为非字符串类型输出
print(sorted(student_objects, key=lambda student: student.grade))  # 按对象的garde属性进行排序
print('-' * 50)

from operator import itemgetter, attrgetter

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]

# operator 库函数 自定义排序  itemgetter(),attrgetter()
print(sorted(student_tuples, key=itemgetter(2)))  # 按2号下标进行排序 lambda x:x[2] 等价
print(sorted(student_objects, key=attrgetter('grade')))  # 按对象的garde属性进行排序 lambda x:x.grade 等价
print('-' * 50)

# 多层排序：
print(sorted(student_tuples, key=itemgetter(0, 2)))  # 先按0号下标排序，再按2号下标排序
print(sorted(student_tuples, key=lambda student: student[0::1]))  # 使用切片，与上述等效
print(sorted(student_objects, key=attrgetter('grade', 'age')))  # 先按grade属性排序，再按age属性排序
print(sorted(student_objects, key=lambda student: (student.grade, student.age)))  # 与上述等效
print('-' * 50)

# 升序，降序 添加参数reverse=True
print(sorted(student_objects, key=lambda student: (student.grade, student.age), reverse=True))
print('-' * 50)

# 排序稳定性
data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
print(sorted(data, key=itemgetter(0)))  # 相同元素不改变优先级次序
print('-' * 50)

# 字典中嵌套list 排序
mydict = {'Li': ['M', 7],
          'Zhang': ['E', 2],
          'Wang': ['P', 3],
          'Du': ['C', 2],
          'Ma': ['C', 9],
          'Zhe': ['H', 7]}
print(sorted(mydict.items(), key=lambda v: v[1][1]))  # dict.items() 所有（key,value）元组列表 按此列表1号下标元素（嵌套的列表）1号下标元素进行排序
print('-' * 50)
# list中混合字典排序
gameresult = [
    {"name": "Bob", "wins": 10, "losses": 3, "rating": 75.00},
    {"name": "David", "wins": 3, "losses": 5, "rating": 57.00},
    {"name": "Carol", "wins": 4, "losses": 5, "rating": 57.00},
    {"name": "Patty", "wins": 9, "losses": 3, "rating": 71.48}]
print(sorted(gameresult, key=itemgetter("rating", "name")))
print('-' * 50)

# 按一个升序，一个降序
tuples = [(3, 5), (1, 2), (2, 4), (3, 1), (1, 3)]
# 使用 sorted 函数进行排序，结合 lambda 表达式定义排序规则
sorted_tuples = sorted(tuples, key=lambda x: (x[0], -x[1]))  # 只有数值型才能操作
print(sorted_tuples)
